
import { Form, Upload } from 'antd';
import {
  PlusOutlined
} from '@ant-design/icons';
import { useEffect, useState, useContext } from 'react';
import { UpdateContext } from '@/store/updateContext';

function FileUpload({ form, name, label, onConfigEvent }) {

  const updateCtx = useContext(UpdateContext)
  const [files, setFiles] = useState([])

  const handleChange = (e) => {

    setFiles(e.fileList)

    let newFiles = e.fileList.filter(item => item.status == 'done').map(item => item.response.url).join(',')
    onConfigEvent(name, newFiles)
  }


  // 上传的图像有变化时，更新对应的name字段的值
  const normFile = (e) => {
    let fileUrl = []
    e.fileList.forEach(file => {

      // 上传成功-->respones后端有返回值
      if (file.response) {
        fileUrl.push(file.response.url)
      }

    })

    // 用 , 拼接多文件（后端只能接字符串？
    return fileUrl.join(',')
  }

  useEffect(() => {
    // 初始值
    let value = form.getFieldValue(name)
    if (!value) {
      setFiles([])
      return
    }

    let newFiles = value.split(',').map(url => {
      return {
        name: '图像',
        status: 'done',
        response: {
          code: 0,
          file: '图像',
          url
        },
        url
      }
    })

    setFiles(newFiles)
  }, [updateCtx.updateFlag])

  return (
    <Form.Item
      label={label}
      name={name}
      getValueFromEvent={normFile}
    >
      <Upload
        action="http://yykj.caihongy.cn/precodegen/sys/oss/upload"
        headers={{ Token: localStorage.getItem('Token') }}
        listType='picture-card'
        maxCount={1}
        accept='image/*'
        fileList={files}
        onChange={handleChange}
        onPreview={() => { }}
      >
        <button
          style={{
            border: 0,
            background: 'none',
          }}
          type="button"
        >
          <PlusOutlined />
          <div
            style={{
              marginTop: 8,
            }}
          >
            上传
          </div>
        </button>
      </Upload>
    </Form.Item>

  )
}

export default FileUpload